package com.runa.rccprotocol.dto.hdrx;

import com.runa.protocol.dto.DtuReportAck;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.util.ByteUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

public class HDRXAck extends DtuReportAck {

    private static final Logger logger = LoggerFactory.getLogger(HDRXAck.class);

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public HDRXAck(String sn, String key) {
        data = new byte[sn.length()+6];
        data[0] = (byte) 0xAA;
        data[1] = 0x72;
        ByteUtil.shortToByte((short) (data.length-2), data, 2, ByteOrder.BA);
        data[4] = 0x10;
        data[5] = (byte) (sn.length() / 2);
        byte[] snByte = ByteUtil.hexStringToByte(sn);
        System.arraycopy(snByte, 0, data, 6, snByte.length);
        byte[] body = new byte[13+snByte.length];
        body[0] = (byte) snByte.length;
        System.arraycopy(snByte, 0, body, 1, snByte.length);
        body[snByte.length+1] = 9;
        body[body.length-1] = ByteUtil.sum(body, 0, body.length-1);
        body = encrypt(body, 0, body.length, key);
        byte[] tail = new byte[2];
        tail[0] = ByteUtil.sum(data, 0, data.length-2);
        tail[1] = (byte) 0xDD;
        data = ByteUtil.merge(data, body, tail);
    }

    public byte[] encrypt(byte[] hex, int off, int len, String key) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
            return cipher.doFinal(hex, off, len);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    public static void main(String[] args) {
        HDRXAck ack = new HDRXAck("10211001869691071584573F", "FUMXRNPXFUMXRNPX");
        System.out.println(ByteUtil.byteToHexString(ack.data));
    }

}
